/**
 * Created by shudong.msd(风骐) on 2016/4/27.
 */

'use strict';

var commUtils = function(){

    var userInfo = JSON.parse(sessionStorage.getItem('userInfo'));

    this.getUserInfo = function(){
        userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
        return userInfo;
    };

    this.getTocken = function(){
        // 更新userInfo
        userInfo = JSON.parse(sessionStorage.getItem('userInfo'));

        this.checkAndUpdateToken();

        return userInfo.access_token;
    };

    //判断是否过期
    var isExpire = function(){
        var exptime = userInfo.expires_time;
        var timestamp = (new Date()).valueOf();
        return timestamp >= exptime;
    };

    //检查并更新token
    this.checkAndUpdateToken = function(){
        if(isExpire()){
            //如果过期，需要重新申请
            var b64 = new Base64();
            var tmpPwd = b64.decode(userInfo.pwd);
            $.ajax({
                type: "POST",
                url: UrlMappings.LOGIN,
                data: {
                    'username':userInfo.name,
                    'password':tmpPwd
                },
                dataType:'json',
                async:false,//同步执行  【同步可能会有问题】
                headers : {
                    'Accept':'text/html',
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                success: function(data){
                    //存储用户信息
                    var userInfo = {'name':data['username'],
                        'pwd':b64.encode(tmpPwd),
                        'last_login_time':new Date(data['last_login_time']).Format("yyyy年MM月dd日 hh:mm:ss"),
                        'access_token':data['access_token'],
                        'token_type':data['token_type'],
                        'refresh_token':data['refresh_token'],
                        'expires_in':data['expires_in'],
                        'scope':data['scope']};

                    //计算token失效时间
                    var timestamp = (new Date()).valueOf();
                    userInfo['expires_time'] = timestamp+(data['expires_in']-300)*1000;//提前一点时间，防止出现遗漏

                    sessionStorage.setItem('userInfo',JSON.stringify(userInfo));
                }
            });


        }
    };

    this.transcateData = function(data){
        data['ages'] = data['age'];
        data['regions'] = data['area'];
        data['channels'] = data['channel'];
        data['tvTypes'] = data['fullType'];
        data['languages'] = data['language'];
        data['tvNames'] = data['programme'];
        data['cities'] = data['region'];
        data['stars'] = data['star'];
        data['terminals'] = data['terminal'];

        delete data['age'];
        delete data['area'];
        delete data['channel'];
        delete data['fullType'];
        delete data['language'];
        delete data['programme'];
        delete data['region'];
        delete data['star'];
        delete data['terminal'];

        // 处理日期为id格式
        if(data['isWeek']!=null){
            var dateList = [];
            if(data['isWeek']==1){
                for(var i in data['timeRange']){
                    var tmpId = data['timeRange'][i];
                    var tmpName = tmpId.substring(0,4)+'/'+tmpId.substring(4,6)+'/'+tmpId.substring(6,8)+'~'+tmpId.substring(13,15)+'/'+tmpId.substring(15,17);
                    dateList.push({'id':tmpId,'name':tmpName});
                }
            }else if(data['isWeek']==0){
                for(var i in data['timeRange']){
                    var tmpId = data['timeRange'][i];
                    var tmpName = tmpId.substring(0,4)+'/'+tmpId.substring(4,6)+'/'+tmpId.substring(6,8);
                    dateList.push({'id':tmpId,'name':tmpName});
                }
            }
            data['timeRange'] = dateList;
        }

        //将 其它 放在最后一项
        var qitaItems = ['regions','channels','tvTypes','languages','tvNames','cities','stars','terminals'];
        for(var i in qitaItems){
            var isExist = false;
            if(isJson(data[qitaItems[i]])){
                for(var j in data[qitaItems[i]]['']){
                    if(data[qitaItems[i]][''][j].name=='其他'){
                        var delIte = data[qitaItems[i]][''].splice(j,1);
                        isExist = true;
                        break;
                    }
                }
                if(isExist){
                    data[qitaItems[i]][''].push(delIte[0]);
                }
            }else{
                for(var j in data[qitaItems[i]]){
                    if(data[qitaItems[i]][j].name=='其他'){
                        var delIte = data[qitaItems[i]].splice(j,1);
                        isExist = true;
                        break;
                    }
                }
                if(isExist){
                    data[qitaItems[i]].push(delIte[0]);
                }
            }

        }

        return data;
    };

    function isJson(obj) {
        return typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
    }

    this.getSearchData = function(){
        return JSON.parse(sessionStorage.getItem('searchData'));
    }

    this.recDatatoSubmit = function(data){

        data['age'] = data['ages'];
        data['area'] = data['regions'];
        data['channel'] = data['channels'];
        data['fullType'] = data['tvTypes'];
        data['language'] = data['languages'];
        data['programme'] = data['tvNames'];
        data['region'] = data['cities'];
        data['star'] = data['stars'];
        data['terminal'] = data['terminals'];

        delete data['ages'];
        delete data['regions'];
        delete data['channels'];
        delete data['tvTypes'];
        delete data['languages'];
        delete data['tvNames'];
        delete data['cities'];
        delete data['stars'];
        delete data['terminals'];

        //处理时间
        /*if(data['timeRange']!=undefined&&data['timeRange'].length>0){
            var dates = data['timeRange'].sort();
            data['startTime'] = dates[0];
            data['endTime'] = dates[dates.length-1];
            delete data['timeRange'];
        }*/

        return data;
    };

    this.logout = function(state){
        sessionStorage.removeItem('userInfo');
        sessionStorage.removeItem('stateType');
        sessionStorage.removeItem('searchData');

        state.go('login',{reload:true});
    }


};